package net.huadong.packet;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.logging.Logger;

/**
 * netty 客户端消息处理
 */
public class NettyPacketTimeClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = Logger.getLogger(NettyPacketTimeClientHandler.class.getName());
    private  byte[] req;
    private int count;
    public NettyPacketTimeClientHandler() {
        req = "QUERY_TIME_ORDER".getBytes();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        /**
         * 这里不间断发送100次命令，会造成tcp的粘包或者拆包
         */
        ByteBuf message = null;
        for(int i=0 ;i<100; i++){
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
            ctx.writeAndFlush(message);
        }

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);
        String body = new String(req, "UTF-8");



        System.out.println("客户端接收到信息：" + body +"    计数："+ ++count);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warning("释放资源：" + cause.getMessage());
        ctx.close();
    }
}
